package com.yy.young.common.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

/**
 * 日期处理工具类
 * 
 */
public class DateUtil {

	// public static final String defaultDatePattern = "yyyy-MM-dd HH:mm:ss";

	public static final String defaultDatePattern = "yyyy-MM-dd HH:mm:ss.SSS";

	public static final String defaultTimestampPattern = "yyyy-MM-dd HH:mm:ss.SSS";

	public static final int NEXT_WORKING_DAY = 1;

	public static final int BEFORE_WORKING_DAY = -1;

	public List ls = new ArrayList();

	/**
	 * 转换非法字符，目前是把单引号转成双引号
	 * 
	 * @param parm
	 * @return
	 */
	public static String conversionInvalid(String parm) {
		return parm.replaceAll("'", "''");
	}

	/**
	 * 按照客户端日期格式转化日期，如：2005-11-07T16:21:27.123
	 * 
	 * @param dateObj
	 *            Object 日期对象
	 * @return String
	 * @version 0.1/2005-11-7
	 */
	public static String dateFormatForClient(Object dateObj) {
		String date = dateFormat(dateObj, defaultTimestampPattern);
		return date == null ? null : date.replace(' ', 'T');
	}

	/**
	 * 将日期对象格式化成字符串
	 * 
	 * @param dateObj
	 *            日期对象 Date/Calendar
	 * @return String 格式化的日期表示
	 */
	public static String dateFormat(Object dateObj) {
		return dateFormat(dateObj, null);
	}

	/**
	 * 将日期对象格式化
	 * 
	 * @param dateObj
	 *            日期对象 Date/Calendar
	 * @param pattern
	 *            日期和时间的表示格式
	 * @return String 格式化的日期表示
	 */
	public static String dateFormat(Object dateObj, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(
				(pattern == null) ? defaultDatePattern : pattern, Locale.CHINA);
		if (dateObj == null) {
			return null;
		} else if (dateObj instanceof Calendar) { // Calendar
			Date date = ((Calendar) dateObj).getTime();
			return sdf.format(date);
		} else if (dateObj instanceof java.sql.Date) {
			Date date = new Date(((java.sql.Date) dateObj).getTime());
			return sdf.format(date);
		} else if (dateObj instanceof java.sql.Time) {
			Date date = new Date(((java.sql.Time) dateObj).getTime());
			return sdf.format(date);
		} else if (dateObj instanceof Timestamp) {
			Date date = new Date(
					((Timestamp) dateObj).getTime());
			sdf = new SimpleDateFormat(
					(pattern == null) ? defaultTimestampPattern : pattern,
					Locale.CHINA);
			return sdf.format(date);
		} else if (dateObj instanceof Date) { // date
			return sdf.format((Date) dateObj);
		} else {
			return null;
		}
	}

	/**
	 * 根据输入的日期字符串按照默认日期格式（yyyy-MM-dd HH:mm:ss.SSS），构造日期对象（Date）并返回
	 * 
	 * @param dateStr
	 *            String 日期字符串，如：2005-01-01 12:00:00.000
	 * @return Date
	 */
	public static Date toDate(String dateStr) {
		return toDate(dateStr, null);
	}

	/**
	 * 根据输入的日期字符串构造日期对象，并返回
	 * 
	 * @param dateStr
	 *            String 日期字符串，如：2005-01-01 12:00:00.000
	 * @param pattern
	 *            String 日期格式
	 * @return Date
	 */
	public static Date toDate(String dateStr, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(
				(pattern == null) ? defaultDatePattern : pattern, Locale.CHINA);
		Date dateReturn = null;
		try {
			dateReturn = sdf.parse(dateStr);
		} catch (ParseException e) {
			System.out.println("unknown date format:" + dateStr);
		}
		return dateReturn;
	}

	/**
	 * 根据输入的日期字符串按照默认日期格式（yyyy-MM-dd HH:mm:ss），构造日历对象（Calendar）并返回
	 * 
	 * @param dateStr
	 *            String 日期字符串，如：2005-01-01 12:00:00.000
	 * @return Calendar
	 */
	public static Calendar toCalendar(String dateStr) {
		return toCalendar(dateStr, null);
	}

	/**
	 * 根据输入的日期字符串构造日历对象（Calendar）并返回
	 * 
	 * @param dateStr
	 *            String 日期字符串，如：2005-01-01 12:00:00.000
	 * @param pattern
	 *            String 日期格式
	 * @return
	 */
	public static Calendar toCalendar(String dateStr, String pattern) {
		Date date = toDate(dateStr, pattern);
		Calendar calendarReturn = Calendar.getInstance();
		calendarReturn.setTime(date);
		return calendarReturn;
	}

	/**
	 * 将时间戳转化成ORACLE的日期格式
	 * 
	 * @param timestamp
	 *            String 日期字符串 2005-01-01 12:10:11.123
	 * @return String ORACLE格式日期 TO_TIMESTAMP('2005-01-01
	 *         12:10:11.123','yyyy-mm-dd hh24:mi:ssxff')
	 * @version 0.2/2005-12-20
	 */
	public static String formatTimestamp(String timestamp) {
		if (timestamp == null)
			return null;
		else if (timestamp.indexOf('.') > 0) { // timestamp
			return "TO_TIMESTAMP('" + timestamp
					+ "','yyyy-mm-dd hh24:mi:ssxff')";
		} else
			// date
			return "TO_DATE('" + timestamp + "','yyyy-mm-dd hh24:mi:ss')";
	}

	/**
	 * 将日期转化成ORACLE的日期格式
	 * 
	 * @param date
	 *            String 2005-01-01
	 * @return String TO_DATE('2005-01-01','yyyy-mm-dd')
	 */
	public static String formatDate(String date) {
		if (date == null)
			return null;
		StringBuffer result = new StringBuffer();
		result.append("TO_DATE('");
		int indexFirstSpace = date.indexOf(' ');
		if (indexFirstSpace > 0) {
			result.append(date.substring(0, indexFirstSpace));
		} else {
			result.append(date);
		}
		result.append("','yyyy-mm-dd')");
		return result.toString();
	}

	/**
	 * 将日期时间转化成ORACLE的日期格式
	 * 
	 * @param dateTime
	 *            String 2005-01-01 12:10:11
	 * @return String TO_DATE('2005-01-01 12:10:11','yyyy-mm-dd hh24:mi:ss')
	 */
	public static String formatDatetime(String dateTime) {
		if (dateTime == null)
			return null;

		StringBuffer result = new StringBuffer();
		result.append("TO_DATE('");
		int indexFirstSpot = dateTime.indexOf('.');
		if (indexFirstSpot > 0) {
			result.append(dateTime.substring(0, indexFirstSpot));
		} else {
			result.append(dateTime);
		}
		result.append("','yyyy-mm-dd hh24:mi:ss')");
		return result.toString();
	}

	/**
	 * 计算两个日期之间相差的天数 if date1 > date2 返回正数 else if date1 < date2 返回负数 else 返回 0
	 * 
	 * @param date1
	 *            java.util.Date
	 * @param date2
	 *            java.util.Date
	 * @return int
	 */
	public static int diffDate(Date date1, Date date2) {
		GregorianCalendar gc1 = new GregorianCalendar();
		GregorianCalendar gc2 = new GregorianCalendar();
		gc1.setTime(date1);
		gc2.setTime(date2);
		return getDays(gc1, gc2);
	}

	/**
	 * 计算两个日期之间相差的小时 if date1 > date2 返回正数 else if date1 < date2 返回负数 else 返回 0
	 * 
	 * @param date1
	 *            java.util.Date
	 * @param date2
	 *            java.util.Date
	 * @return int
	 */
	public static long diffHour(Date date1, Date date2) {
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		return (time1 - time2) / (1000 * 3600);
	}

	public static int getDays(GregorianCalendar g1, GregorianCalendar g2) {
		int elapsed = 0;
		GregorianCalendar gc1, gc2;

		if (g2.after(g1)) {
			gc2 = (GregorianCalendar) g2.clone();
			gc1 = (GregorianCalendar) g1.clone();
		} else {
			gc2 = (GregorianCalendar) g1.clone();
			gc1 = (GregorianCalendar) g2.clone();
		}

		gc1.clear(Calendar.MILLISECOND);
		gc1.clear(Calendar.SECOND);
		gc1.clear(Calendar.MINUTE);

		gc2.clear(Calendar.MILLISECOND);
		gc2.clear(Calendar.SECOND);
		gc2.clear(Calendar.MINUTE);

		while (gc1.before(gc2)) {
			gc1.add(Calendar.HOUR_OF_DAY, 1);
			elapsed++;
		}

		return g1.after(g2) ? elapsed / 24 : -elapsed / 24;
	}

	public static int diffDate1(Date date1, Date date2) {
		GregorianCalendar gc1 = new GregorianCalendar();
		GregorianCalendar gc2 = new GregorianCalendar();
		gc1.setTime(date1);
		gc2.setTime(date2);
		return getDays1(gc1, gc2);
	}

	public static int getDays1(GregorianCalendar g1, GregorianCalendar g2) {
		int elapsed = 0;
		GregorianCalendar gc1, gc2;

		if (g2.after(g1)) {
			gc2 = (GregorianCalendar) g2.clone();
			gc1 = (GregorianCalendar) g1.clone();
		} else {
			gc2 = (GregorianCalendar) g1.clone();
			gc1 = (GregorianCalendar) g2.clone();
		}

		gc1.clear(Calendar.MILLISECOND);
		gc1.clear(Calendar.SECOND);
		gc1.clear(Calendar.MINUTE);
		if (gc1.HOUR < gc2.HOUR) {
		}
		gc1.set(gc1.HOUR_OF_DAY, 0);

		gc2.clear(Calendar.MILLISECOND);
		gc2.clear(Calendar.SECOND);
		gc2.clear(Calendar.MINUTE);
		gc2.set(gc2.HOUR_OF_DAY, 0);

		while (gc1.before(gc2)) {
			gc1.add(Calendar.DATE, 1);
			elapsed++;
		}

		return g1.after(g2) ? elapsed : -elapsed;
	}

	/**
	 * 相对与gc的一周的第一天
	 */
	public static GregorianCalendar getFirstWeekday(GregorianCalendar gc) {
		gc.add(Calendar.DAY_OF_MONTH, -(gc.get(Calendar.DAY_OF_WEEK) - 1));
		return gc;
	}

	/**
	 * 相对与gc的一月的第一天
	 */
	public static GregorianCalendar getFirstMonth(GregorianCalendar gc) {
		gc.set(Calendar.DAY_OF_MONTH, 1);
		return gc;
	}

	/**
	 * 相对与gc的一年的第一天
	 */
	public static GregorianCalendar getFirstYear(GregorianCalendar gc) {
		gc.set(Calendar.MONTH, 0);
		gc.set(Calendar.DAY_OF_MONTH, 1);
		return gc;
	}
	/** 
	  * 指定日期前几天或者后几天的日期 
	  * @param n 
	  * @return 
	  */  
	public static String afterNDay(Date date ,int n,String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, n);
		String sDate = dateFormat.format(calendar.getTime());
		return sDate;
	}

	public static String getCurrentDay(){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		return sf.format(new Date());
	}

	public static String getCurrentTime(){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sf.format(new Date());
	}
	
	//获取当前年度
	public static int getCurrentYear() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.YEAR);
	}
	public static int getCurrentMonth(){
		Calendar c = Calendar.getInstance();
		int month = c.get(Calendar.MONTH);
		month = month + 1;
		return month;
	}
	//获取当前月最后一天日期
	public static String getCurrentMonthMaxDay(){
		Calendar c = Calendar.getInstance();
		String year = getCurrentYear()+"";
		String month = getCurrentMonth()+"";
		String day = getMaxDay(year,month)+1+"";
		return year+"-"+month+"-"+day;
	}
	// 获取当前季度
	public static int getCurrentQuarter() {
		Calendar c = Calendar.getInstance();
		int month = c.get(Calendar.MONTH);
		month = month + 1;
		int quarter = 0;
		if (month >= 1 && month <= 3) {
			quarter = 1;
		} else if (month >= 4 && month <= 6) {
			quarter = 2;
		} else if (month >= 7 && month <= 9) {
			quarter = 3;
		} else if (month >= 10 && month <= 12) {
			quarter = 4;
		}
		return quarter;
	}
	/**
	 * 获取指定年月的最大天数
	 * @param year 指定年
	 * @param month 指定月
	 * @return
	 */
	public static int getMaxDay(String year,String month){
		Calendar rightNow = Calendar.getInstance();
		rightNow.set(Calendar.YEAR,Integer.parseInt(year));
		rightNow.set(Calendar.MONTH,Integer.parseInt(month));
		int days = rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);
		return days;
	}

	/**
	 * 获取指定年月的周末日期
	 * @param year 指定年
	 * @param month 指定月
	 * @return
	 */
	public static String getWeekEnd(String year,String month){

		StringBuffer sb = new StringBuffer();
		int dayNum = getMaxDay(year,month);
		Calendar calendar = Calendar.getInstance(Locale.CHINA);
		calendar.set(Calendar.YEAR,Integer.parseInt(year));
		calendar.set(Calendar.MONTH,Integer.parseInt(month)-1);
		calendar.set(Calendar.DATE,1);

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
		for (int i = 0; i < dayNum; i++) {
			if(calendar.get(Calendar.DAY_OF_WEEK)==1||calendar.get(Calendar.DAY_OF_WEEK)==7){
				sb.append(sf.format(calendar.getTime())+",");
			}
			calendar.add(Calendar.DATE,1);
		}
		sb.deleteCharAt(sb.length()-1);
		return sb.toString();
	}
}
